package structure;
import java.util.*;

public class Test2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

    }
    //leetcode 24.两两交换链表中的节点
    class Solution2 {
        public ListNode swapPairs(ListNode head) {
            ListNode dummy = new ListNode(0,head);
            ListNode node0 = dummy;
            ListNode node1 = head;
            while(node1 != null && node1.next != null){
                ListNode node2 = node1.next;
                ListNode node3 = node2.next;
                node0.next = node2;
                node2.next = node1;
                node1.next = node3;
                node0 = node1;
                node1 = node3;
            }
            return dummy.next;
        }
    }

    //leetcode 19.删除链表的倒数第N个结点
    class Solution1 {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode cur0 = head;
            ListNode cur1 = head;
            while(n-- > 0){
                cur0 = cur0.next;
                //代表删除第一个数据
                if(cur0 == null){
                    return head.next;
                }
            }
            //找到倒数第N个结点的前一个结点
            while(cur0.next != null){
                cur0 = cur0.next;
                cur1 = cur1.next;
            }
            //跳过倒数第N个结点
            cur1.next = cur1.next.next;
            return head;
        }
    }
    //leetcode 2.两数相加
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode cur = new ListNode();
            ListNode head = cur;
            //代表进位数
            int num = 0;
            while(l1 != null || l2 != null){
                int x = l1 != null ? l1.val : 0;
                int y = l2 != null ? l2.val : 0;
                int sum = x + y + num;
                //进位数重置
                num = 0;
                if(sum < 10){
                    cur.next = new ListNode(sum);
                }else {
                    cur.next = new ListNode(sum % 10);
                    num++;
                }
                cur = cur.next;
                if(l1 != null){
                    l1 = l1.next;
                }
                if(l2 != null){
                    l2 = l2.next;
                }
            }
            //防止最后进位
            if(num == 1){
                cur.next = new ListNode(num);
            }
            return head.next;
        }
    }
}

